﻿CREATE PROCEDURE [dbo].[proc_Loan_Create]
	(
		@CompanyId INT,
		@CompanyName NVARCHAR(10),
		--@DepartmentId INT,
		--@DepartmentName NVARCHAR(10),
		@ENameId VARCHAR(10),
		@EName NVARCHAR(10),
		@PostCategoryId INT,
		@PostCategory  nvarchar(50),
		@Address NVARCHAR(500),
		@Days NVARCHAR(50),
		@Money decimal(18, 2),
		@Cause nvarchar(MAX),
		@PZPerson varchar(10),
		@PZPersonName NVARCHAR(10),
		@SHPerson varchar(10),
		@SHPersonName NVARCHAR(10),
		@lrrq DATETIME,
		@userid varchar(10),
		@username NVARCHAR(10)	,
		@Summary NVARCHAR(100),
		@PaymentTypeId int,
		@PaymentTypeName nvarchar(50),
		@BankId int,
		@BankName nvarchar(50),
		@typeid INT
	)
AS
BEGIN
	
BEGIN TRANSACTION--开始事务
DECLARE @errorSun INT --定义错误计数器
SET @errorSun=0 --没错为0
	
	
	INSERT INTO [Loan]
           ([CompanyId]
           ,[CompanyName]
           ,[DepartmentId]
           ,[DepartmentName]
           ,[ENameId]
           ,[EName]
           ,[PostCategoryId]
           ,[PostCategory]
           ,[Address]
           ,[Days]
           ,[Money]
           ,[Cause]
           ,[PZPerson]
           ,[PZPersonName]
           ,[SHPerson]
           ,[SHPersonName]
           ,[lrrq]
           ,[userid]
           ,[username]
           ,[Summary],
           PaymentTypeId,
		PaymentTypeName,
		BankId,
		BankName,typeid)
     VALUES
           (@CompanyId ,
			@CompanyName ,
			0,
			'',
			@ENameId ,
			@EName,
			@PostCategoryId,
			@PostCategory,
			@Address ,
			@Days ,
			@Money ,
			@Cause ,
			@PZPerson ,
			@PZPersonName,
			@SHPerson ,
			@SHPersonName,
			@lrrq ,
			@userid ,
			@username,
			@Summary,
			@PaymentTypeId,
		@PaymentTypeName,
		@BankId,
		@BankName,@typeid )
		

if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end
DECLARE @pid INT 
--刚插入的借款记录的ID
SET @pid= @@identity

Insert Into Finance_Outlay
	(
		CreateDate,
		TradeDate,
		Summary,
		CateOneId,
		CateOneName,
		CateTwoId,
		CateTwoName,
		SubjectId,
		SubjectName,
		PaymentTypeId,
		PaymentTypeName,
		BankId,
		BankName,
		OutlayReason,
		OutlayPrice,
		Agent,
		AgentName,
		PZPerson,
		PZPersonName,
		SHPerson,
		SHPersonName,
		UserName,
		EName,
		Description,
		BillNumber,
		CompanyId,
		CompanyIdCur,
		DepartmentIdCur,l_id,l_type
	)
	VALUES(
		GETDATE(),
		Convert(varchar(10),GETDATE(),120),
		@Summary,
		17,
		'往来类',
		18,
		'借款',
		203,
		'借款',
		@PaymentTypeId,
		@PaymentTypeName,
		@BankId,
		@BankName,
		@Cause,
		@Money,
		@ENameId,
		@EName,
		@PZPerson,
		@PZPersonName,
		@SHPerson,
		@SHPersonName,
		@userid,
		@username,
		'',
		'',
		@CompanyId,
		@CompanyId,
		0,@pid,'L'
	)
if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
    end

e:
    PRINT @errorSun
	if @errorSun>0
	begin
		rollback TRANSACTION
	
	end
	else
	begin
		commit TRANSACTION
	END
end		
	RETURN
